<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Wechats;
use app\common\model\Members;
use app\common\model\Materials;
use app\common\model\Attachment;
use app\common\model\MessageLogs;
/**
 * 示例接口
 */
class Cgi extends Api
{

     //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['handle', 'test1'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['handle'];
    /*
    * Wechat 入口
    * By Perry Lin 2016年06月13日14:02:59
    */
    public function _initialize()
    {
        $this->wechats = new Wechats;
        $this->token = $this->request->param('token');
        $this->options = $this->wechats->getByToken($this->token);
    }
    public function handle(){
        $weObj = WX($this->options);
        $weObj->valid(); 
        $type = $weObj->getRev()->getRevType();
        $keyword = $weObj->getRev()->getRevContent();
        //获取接收事件推送
        $form = $weObj->getRev()->getRevEvent();
        $form_Event = $form['event'];
        $form_Key = $form['key']; //qrscene_1622
        $msgFrom = $weObj->getRevFrom();
        $WXMessage = $weObj->getRevData();
        switch ($type) {
             //textd
            case $weObj::MSGTYPE_TEXT:
                MessageLogs::addMessage($WXMessage,$this->options['id']);
                //$weObj->text('欢迎关注<a href="weixin://bizmsgmenu?msgmenucontent='.$this->options['wxname'].'&msgmenuid=1">'.$keyword.'</a>')->reply();
                $results = (new \app\common\model\Keywords)->getKeywordItem($keyword,$this->options['id']);
                if(!$results){ //收到消息但没有关键词
                    $mess = db('replys')->where(['wechat_id'=>$this->options['id'],'type'=>'message'])->find();
                    if(!empty($mess)){
                        if($mess['category'] == 'text'){
                            $content = fmtContent($mess['content']);
                            $weObj->text($content)->reply();
                        }else{
                            $media_id = (new Attachment)->getMedia_id($mess['image'],$this->options['id']);
                            if(!empty($media_id)){
                                $weObj->image($media_id)->reply();
                            }
                        }
                    }
                    $weObj->text("没有找到你想要的问题，请重新输入关键词")->reply();
                }

                if(count($results) == 1){ //只有一个问题
                    $data = $results[0];
                    if($data['type'] == 'text'){
                        $weObj->text(fmtContent($data['content']))->reply();
                    }else if($data['type'] == 'image'){
                        $media_id = (new Attachment)->getMedia_id($data['image'],$this->options['id']);
                        if(!empty($media_id)){
                            $weObj->image($media_id)->reply();
                        }
                    }else if($data['type'] == 'mpnews'){
                        $Articles = (new Materials)->getArticles(intval($data['material_id']));
                        if(!empty($Articles)){
                            $weObj->news($Articles)->reply();
                        }
                    }
                }else{
                    $content = "您是否想质询以下问题:\n";
                    foreach ($results as $key => $value) {
                        $keyword = db('keyword_mate')->where('keyword_id',$value['id'])->value('keyword');
                        $content .= '<a href="weixin://bizmsgmenu?msgmenucontent='.$value['name'].'&msgmenuid=1">'.($key+1).". ".$value['name'].'</a>'."\n";
                    }
                    $weObj->text(fmtContent($content))->reply();
                }
                break;
            // IMAGE 
            case $weObj::MSGTYPE_IMAGE:
                MessageLogs::addMessage($WXMessage,$this->options['id']);
                $mess = db('replys')->where(['wechat_id'=>$this->options['id'],'type'=>'message'])->find();
                if(!empty($mess)){
                    if($mess['category'] == 'text'){
                        $content = fmtContent($mess['content']);
                        $weObj->text($content)->reply();
                    }else{
                        $media_id = (new Attachment)->getMedia_id($mess['image'],$this->options['id']);
                        if(!empty($media_id)){
                            $weObj->image($media_id)->reply();
                        }
                    }
                }
                break;
            //event
            case $weObj::MSGTYPE_EVENT:
                 switch(strtolower($form_Event)){
                     /*粉丝关注*/
                    case 'subscribe':
                        // 获取用户信息
                        $access_token = $this->wechats->Token_Access($this->options);
                        if($access_token){
                            $data = $weObj->getUserInfo($msgFrom,$access_token);    
                            $member = Members::getByOpenid($msgFrom);
                            if(isset($member['id'])){
                                $data['update_at'] = time();
                                Members::where('id',$member['id'])->update($data);
                            }else{
                                $data['wechat_id'] = $this->options['id'];
                                $data['update_at'] = time();
                                Members::insert($data);
                            }
                        }
                        $result = db('replys')->where(['wechat_id'=>$this->options['id'],'type'=>'follow'])->find();
                        if(isset($result['category']) && $result['category'] == 'text'){
                            $content = fmtContent($result['content']);
                            $weObj->text($content)->reply();   
                            return '';
                        }
                        if(isset($result['category']) && $result['category'] == 'image'){
                            if(!empty($result['media_id'])){
                                $weObj->image($result['media_id'])->reply();
                                 return '';
                            }
                            
                        }
                        $concern = '欢迎关注'.$this->options['wxname'].'';
                        $weObj->text($concern)->reply();
                        break;
                    /*取消关注*/
                    case 'unsubscribe':
                        Members::where('openid',$msgFrom)->update(['update_at'=>time(),'subscribe'=>0]);
                        break;
                    case 'click':
                        $concern = "";
                        
                        $menu = db('wx_menu')->where(['menu_id'=>intval($form_Key)])->find();
                        if(!empty($menu)){
                            $opt = json_decode($menu['options'],true);
                            // 回复文字内容
                            if(isset($opt['type']) && $opt['type'] == 'text'){
                                $concern = fmtContent($opt['content']);
                                //$weObj->text(fmtContent($opt['content']))->reply();
                            }
                            // 回复图片
                            if(isset($opt['type']) && $opt['type'] == 'image' && !empty($opt['media_id'])){
                                $media_id = (new Attachment)->getMedia_id($opt['image'],$this->options['id']);
                                if(!empty($media_id)){
                                    $weObj->image($media_id)->reply();
                                }
                            }
                            // 回复图文
                            if(isset($opt['type']) && $opt['type'] == 'mpnews'){
                                $Articles = (new Materials)->getArticles(intval($opt['material_id']));
                                if(!empty($Articles)){
                                    $weObj->news($Articles)->reply();
                                }
                            }
                        }
                        
                        if(empty($concern)){
                            $mess = db('replys')->where(['wechat_id'=>$this->options['id'],'type'=>'message'])->find();
                            if(!empty($mess)){
                                if($mess['category'] == 'text'){
                                    $content = fmtContent($mess['content']);
                                    $weObj->text($content)->reply();
                                }else{
                                    $media_id = (new Attachment)->getMedia_id($mess['image'],$this->options['id']);
                                    if(!empty($media_id)){
                                        $weObj->image($media_id)->reply();
                                    }
                                }
                            }
                            $weObj->text("没有找到你想要的问题，请重新输入关键词")->reply();
                        }
                        $weObj->text($concern)->reply();
                        break;
                 }
                break;
        }
    }
}